package it.koutifaris.travianmap;

import it.koutifaris.travianmap.gui.MapView;
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class TravianMap extends Activity {

	private static final int GO_TO_DIALOG = 0;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.main_menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.go_to:
			showDialog(GO_TO_DIALOG);
			return true;
		case R.id.exit:
			this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		MapView mapView = getMapView();
		EditText gotoX = (EditText) dialog.findViewById(R.id.gotoX);
		EditText gotoY = (EditText) dialog.findViewById(R.id.gotoY);
		// Point center = new Point(mapView.getdX()+mapView.getWidth()/2, mapView.getdY()+mapView.getHeight()/2);
		// Point sqCoords = mapView.getSqCoords();
		// gotoX.setText(String.valueOf(sqCoords.x));
		// gotoY.setText(String.valueOf(sqCoords.y));
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		Dialog dialog;
		switch (id) {
		case GO_TO_DIALOG:
			dialog = createGotoDialog();
			break;
		default:
			dialog = null;
			break;
		}
		return dialog;
	}

	private Dialog createGotoDialog() {
		final Dialog dialog = new Dialog(this);
		dialog.setTitle(R.string.go_to_title);
		dialog.setContentView(R.layout.go_to_dialog);
		Button ok = (Button) dialog.findViewById(R.id.OK_GOTO);
		ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				EditText gotoX = (EditText) dialog.findViewById(R.id.gotoX);
				EditText gotoY = (EditText) dialog.findViewById(R.id.gotoY);
				int x = Integer.parseInt(gotoX.getText().toString());
				int y = Integer.parseInt(gotoY.getText().toString());
				Log.i(this.getClass().getName(), "(" + x + ";" + y + ")");
				getMapView().animateTo(x, y);
				// getMapView().setdX(getMapView().getdX()+getMapView().getWidth()/2);
				// getMapView().setdY(getMapView().getdY()+getMapView().getHeight()/2);
				getMapView().invalidate();
				dialog.dismiss();
			}
		});
		return dialog;
	}

	private MapView getMapView() {
		return (MapView) this.findViewById(R.id.mapView);
	}

}